package demo.thread;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;

// 实现一个容器，提供两个方法，add，size 写两个线程，线程1添加10个元素到容器中，线程2实现监控元素的个数，当个数到5个时，线程2给出提示并结束.
public class _监控容量 {
    static volatile List<Integer> list = new ArrayList<>();

    public static void main(String[] args) {
//        m1();
        m2();
    }

    private static void m2() {
        CountDownLatch countDownLatch = new CountDownLatch(1);
        new Thread(() -> {
            System.out.println("t2启动");
            if (list.size() != 5) {
                try {
                    countDownLatch.await();
                    System.out.println("t2结束");
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }, "t2").start();
        new Thread(() -> {
            System.out.println("t1开始");
            for (int i = 0; i < 10; i++) {
                System.out.println("add:" + i);
                list.add(i);
                if (list.size() == 5) {
                    countDownLatch.countDown();
                }
            }
            System.out.println("t1结束");
        }, "t1").start();

    }

    private static void m1() {
        Object lock = new Object();
        new Thread(() -> {
            System.out.println("t2启动");
            synchronized (lock) {
                if (list.size() < 5) {
                    try {
                        lock.wait();
                        System.out.println("t2结束");
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
                lock.notify();
            }
        }, "t2").start();

        new Thread(() -> {
            System.out.println("t1启动");
            synchronized (lock) {
                for (int i = 0; i < 10; i++) {
                    list.add(i);
                    System.out.println("add:" + i);
                    if (list.size() == 5) {
                        lock.notify();
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                }

            }
        }, "t1").start();
    }
}
